﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.ComponentModel;
using Axe.Extensions;
using System.Web.Configuration;
using Axe.Web.Controls.Configuration;
using System.Web;
using System.Web.UI.WebControls;
using System.Diagnostics;
using AjaxControlToolkit;
using System.Web.UI.HtmlControls;

namespace Axe.Web.Controls
{
    public enum WikiContentControlIdentifierMode
    {
        PageLocal,
        SiteGlobal
    }

    [ToolboxData("<{0}:WikiContentControl runat=server></{0}:WikiContentControl>")]
    public class WikiContentControl : CompositeControl, IPostBackEventHandler
    {
        WikiContentProvider providerInstance;

        [Category("Wiki")]
        [DefaultValue("")]
        [Description("Defines wiki content identifer")]
        public string ContentKey
        {
            get { return ViewState.Get("WikiContentKey", ""); }
            set { ViewState["WikiContentKey"] = value; }
        }

        [Category("Wiki")]
        [DefaultValue(WikiContentControlIdentifierMode.PageLocal)]
        public WikiContentControlIdentifierMode Mode
        {
            get { return ViewState.Get("WikiContentControlIdentifierMode", WikiContentControlIdentifierMode.PageLocal); }
            set { ViewState["WikiContentControlIdentifierMode"] = value; }
        }

        [Category("Wiki")]
        [DefaultValue("Edit...")]
        public string EditLinkText
        {
            get { return ViewState.Get("EditLinkText", "Edit..."); }
            set { ViewState["EditLinkText"] = value; }            
        }

        [Category("Wiki")]
        [DefaultValue("")]
        [CssClassProperty]
        public string WikiTextCssClass
        {
            get { return ViewState.Get("WikiTextCssClass", String.Empty); }
            set { ViewState["WikiTextCssClass"] = value; }
        }

        [Category("Wiki")]
        [DefaultValue("")]
        [CssClassProperty]
        public string EditLinkCssClass
        {
            get { return ViewState.Get("EditLinkCssClass", String.Empty); }
            set { ViewState["EditLinkCssClass"] = value; }
        }

        [DefaultValue("span")]
        [Category("Wiki")]
        public string WikiTextTag
        {
            get { return ViewState.Get("WikiTextTag", "span"); }
            set { ViewState["WikiTextTag"] = value; }
        }

        [Category("Wiki"),CssClassProperty]
        public string BackgroundCssClass
        {
            get { return ViewState.Get("BackgroundCssClass", config.Appearance.BackgroundCssClass); }
            set { ViewState["BackgroundCssClass"] = value; }
        }

        [Category("Wiki"), CssClassProperty]
        public string ModalPopupCssClass
        {
            get { return ViewState.Get("ModalPopupCssClass", config.Appearance.ModalPopupCssClass); }
            set { ViewState["ModalPopupCssClass"] = value; }
        }


        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (!DesignMode)
            {
                config = AxeControlsConfigurationSection.Configuration.WikiControlConfiguration;
                WikiContentProviderConfiguration provider = config.Providers.GetProvider(config.DefaultProvider);

                Type providerType = Type.GetType(provider.Type);
                providerInstance = (WikiContentProvider)Activator.CreateInstance(providerType);
                providerInstance.Initialize(provider.Name, provider.InitializationParams);
                providerInstance.RegisterWikiControl(ContentKey, Page, Mode);
            }
        }

        WikiConfiguration config;
        HtmlGenericControl wikiText;
        LinkButton editLink;
        Panel editPanel;
        TextBox tbWikiTextEdit;
        Button saveChanges;
        Button cancelChanges;
        ModalPopupExtender mppe;

        protected override void CreateChildControls()
        {
            Controls.Clear();
            ClearChildViewState();

            wikiText = new HtmlGenericControl(WikiTextTag);

            if (DesignMode)
            {
                wikiText.InnerHtml = String.Format("Wiki Resource: {0}", ContentKey);
            }

            Controls.Add(wikiText);

            if (IsInEditMode)
            {
                editLink = new LinkButton();
                editLink.ID = "WikiEditLink";
                editLink.Text = EditLinkText;
                //editLink.EnableViewState = false;

                Controls.Add(editLink);

                editPanel = new Panel();
                editPanel.ID = "WikiEditPanel";
                editPanel.Width = Unit.Pixel(500);
                editPanel.Height = Unit.Pixel(350);
                editPanel.Style.Add(HtmlTextWriterStyle.TextAlign, "center");

                tbWikiTextEdit = new TextBox();
                tbWikiTextEdit.ID = "WikiContentEditArea";
                tbWikiTextEdit.TextMode = TextBoxMode.MultiLine;
                tbWikiTextEdit.Width = Unit.Pixel(500);
                tbWikiTextEdit.Height = Unit.Pixel(300);
                //tbWikiTextEdit.EnableViewState = false;

                saveChanges = new Button();
                saveChanges.ID = "WikiSaveChanges";
                saveChanges.Text = "Save";

                cancelChanges = new Button();
                cancelChanges.ID = "WikiCancelChanges";
                cancelChanges.Text = "Cancel";

                editPanel.Controls.Add(tbWikiTextEdit);
                editPanel.Controls.Add(new LiteralControl("<br/>"));
                editPanel.Controls.Add(saveChanges);
                editPanel.Controls.Add(cancelChanges);
                
                mppe = new ModalPopupExtender();
                mppe.ID = "WikiEditPopup";
                mppe.PopupControlID = editPanel.ID;
                mppe.OkControlID = saveChanges.ID;
                mppe.CancelControlID = cancelChanges.ID;
                mppe.TargetControlID = editLink.ID;

                Controls.Add(editPanel);
                Controls.Add(mppe);
            }

            ChildControlsCreated = true;
        }


        protected override void OnPreRender(EventArgs e)
        {
            wikiText.Style["class"] = WikiTextCssClass;

            if(!DesignMode)
            {
                wikiText.InnerHtml = providerInstance.GetContent(ContentKey, Page, Mode);

                if (IsInEditMode)
                {
                    editLink.CssClass = EditLinkCssClass;
                    mppe.BackgroundCssClass = BackgroundCssClass;
                    editPanel.CssClass = ModalPopupCssClass;    
                }

            }

            base.OnPreRender(e);

        }

        protected override void Render(HtmlTextWriter writer)
        {

           
            if (IsInEditMode)
            {
                tbWikiTextEdit.Text = wikiText.InnerHtml;

                String textGet = String.Format("document.getElementById('{0}').innerText", 
                    tbWikiTextEdit.ClientID);

                //string a = Page.ClientScript.GetPostBackClientHyperlink(this, "");

                saveChanges.OnClientClick = String.Format("__doPostBack('{0}',{1});",
                    this.UniqueID,
                    textGet);
            }

            base.Render(writer);
        }

        #region IPostBackEventHandler Members

        public void RaisePostBackEvent(string eventArgument)
        {
            providerInstance.UpdateContent(ContentKey, eventArgument, this.Page, Mode);
        }

        #endregion

        public static void EnterEditWikiMode()
        {
            HttpContext.Current.Session.Add("WikiContentControl.EditMode", true);
        }

        public static void LeaveEditWikiMode()
        {
            HttpContext.Current.Session.Remove("WikiContentControl.EditMode");
        }

        public static bool IsInEditMode
        {
            get
            {
                if (HttpContext.Current == null)
                    return false;

                object o = HttpContext.Current.Session["WikiContentControl.EditMode"];
                if(o == null)
                    return false;

                return true == ((bool)o);
            }
        }

    }
}
